<template>
  <section class="todoapp">
    <hm-header @add-event="handleAdd"></hm-header>
    <hm-main :list="showList"
    @delete-event="handleDelete" 
    @change-status-event="changeStatus"
    @change-all-event="handleAll"
    ></hm-main>
    <hm-footer
     :list="list"
     @clearall-event="clearAll"
     :status="status"
     @status-event="status=$event"
    ></hm-footer>
  </section>
</template>

<script>
const obj = {
  "#/": "all",
  "#/completed": "done",
  "#/active": "undone",
};
import HmHeader from './components/hm-header.vue'
import HmMain from './components/hm-main.vue'
import HmFooter from './components/hm-footer.vue'
export default {
  components: {
    HmHeader,
    HmMain,
    HmFooter
  },
  data(){
    return {
      list:JSON.parse(window.localStorage.getItem('list')) || [],
      status:obj[location.hash] || 'all',
    }
  },
  methods:{
    handleDelete(id){
      const index=this.list.findIndex((item)=> item.id === id)
      this.list.splice(index,1)
    },
    changeStatus(id){
      const obj=this.list.find((item)=>item.id ===id)
      obj.done=!obj.done
    },
    handleAdd(name){
      const id =this.list.length===0 ? 1 : this.list.slice(-1)[0].id+1
      const obj={
        id,
        name,
        done:false,
      }
      this.list.push(obj)
    },
    handleAll(value){
      this.list=this.list.map((item)=>{
        item.done=value
        return item
      })
    },
    clearAll(){
      this.list=this.list.filter((item)=> item.done===false)
    },
  },
  computed:{
    showList(){
      if(this.status === 'all'){
        return this.list
      }else if(this.status ==='done'){
        return this.list.filter(item=> item.done===true)
      }else{
        return this.list.filter(item=> item.done===false)
      }
    }
  },
  watch:{
    list:{
      handler(newValue){
        window.localStorage.setItem("list",JSON.stringify(newValue))
      },
      deep:true,
    }
  }
}
</script>

<style></style>
